package com.mindata.blockchain.socket.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.client.intf.ClientAioListener;
import org.tio.core.Aio;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;

import com.mindata.blockchain.ApplicationContextProvider;
import com.mindata.blockchain.core.event.NodesConnectedEvent;

/**
 * client端对各个server连接的情况回调。
 * </p>
 * 当某个server的心跳超时（2min）时，Aio会从group里remove掉该连接，需要在重新connect后重新加入group
 *
 * @author wuweifeng wrote on 2018/3/12.
 */
public class BlockClientAioListener implements ClientAioListener {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void onAfterConnected(final ChannelContext channelContext, final boolean isConnected,
			final boolean isReconnect) throws Exception {
		//        if (isConnected) {
		//            logger.info("连接成功：server地址为-" + channelContext.getServerNode());
		//            Aio.bindGroup(channelContext, Const.GROUP_NAME);
		//        } else {
		//            logger.info("连接失败：server地址为-" + channelContext.getServerNode());
		//        }
		ApplicationContextProvider.publishEvent(new NodesConnectedEvent(channelContext));
	}

	@Override
	public void onBeforeClose(final ChannelContext channelContext, final Throwable throwable, final String s,
			final boolean b) {
		logger.info("连接关闭：server地址为-" + channelContext.getServerNode());
		Aio.unbindGroup(channelContext);
	}

	@Override
	public void onAfterDecoded(final ChannelContext channelContext, final Packet packet, final int i) throws Exception {

	}

	@Override
	public void onAfterReceivedBytes(final ChannelContext channelContext, final int i) throws Exception {

	}

	@Override
	public void onAfterSent(final ChannelContext channelContext, final Packet packet, final boolean b)
			throws Exception {

	}

	@Override
	public void onAfterHandled(final ChannelContext channelContext, final Packet packet, final long l)
			throws Exception {

	}

}
